package codeTop;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class q39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        dfs(res,list,candidates,target,0);
        return res;
    }

    private void dfs(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int idx) {
        if (target == 0) {
            res.add(List.copyOf(list));
            return;
        }
        if (idx == candidates.length) {
            return;
        }
        //跳过
        dfs(res,list,candidates,target,idx+1);
        //不跳过
        if (target>=candidates[idx]){
            list.add(candidates[idx]);
            dfs(res,list,candidates,target-candidates[idx],idx);
            list.remove(list.size()-1);
        }
    }
}
